package com.lyubia.shop.order.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lyubia.shop.common.enums.PayStatus;
import com.lyubia.shop.common.enums.ShipStatus;
import com.lyubia.shop.common.result.BaseResult;
import com.lyubia.shop.order.config.AlipayConfig;
import com.lyubia.shop.order.mapper.OrderMapper;
import com.lyubia.shop.order.pojo.Order;
import com.lyubia.shop.order.service.OrderService;
import com.lyubia.shop.order.service.PayService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public String startPayRequest(String orderSn) {
        Order order = orderService.selectOrderByOrderSn(orderSn);
        if (order == null) {
            System.out.println("订单消息不存在!");
            return null;
        }
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key,
                    "json",
                    AlipayConfig.charset,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type);
            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
            BigDecimal total_amount = BigDecimal.valueOf(1L);
            String subject = "订单支付";
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderSn + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            return  alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 同步回调
     * @param outTradeNo 订单编号
     * @param totalAmount 总金额
     * @param tradeNo 交易流水（支付编号）
     * @param request 请求
     * @return 结果
     */
    @Override
    public BaseResult returnCallback(String outTradeNo,
                                     BigDecimal totalAmount,
                                     String tradeNo,
                                     HttpServletRequest request) {
        try {
            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

            if(signVerified) {
                System.out.println("请求合法...");
                /**
                 * 订单状态更新
                 *    参数: 订单编号  支付宝支付流水  订单金额
                 *   订单更新思路
                 *     I.参数校验
                 *       1.订单记录查询
                 *       2.记录存在校验
                 *       3.订单支付状态校验(未支付)
                 *       4.订单金额校验
                 *     II.订单状态更新
                 */
                Order order = orderService.selectOrderByOrderSn(outTradeNo);
                if(null == order){
                    return BaseResult.error("订单记录不存在!");
                }

                if(order.getPayStatus().equals(PayStatus.has_payed.getStatus())){
                    return BaseResult.success("订单已支付!");
                }

                if(order.getTotalAmount().compareTo(totalAmount) !=0){
                    return BaseResult.error("订单金额异常!");
                }

                // 设置订单支付状态为已支付
                order.setPayStatus(PayStatus.has_payed.getStatus());
                order.setShippingStatus(ShipStatus.has_send.getStatus());
                order.setPayCode(tradeNo);
                order.setPayName("支付宝支付");
                //order.setPayTime(new Date());
                if(orderMapper.updateByPrimaryKeySelective(order) !=1){
                    return  BaseResult.error("订单支付异常，请联系客服!");
                }
                return BaseResult.success();
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    public BaseResult notifyCallback(String outTradeNo, BigDecimal totalAmount, String tradeNo, String tradeStatus, HttpServletRequest request) {
        try {
            //获取支付宝GET过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            if(signVerified) {
                System.out.println("请求合法...");
                // 支付成功时 更新订单状态
                if(tradeStatus.equals("TRADE_SUCCESS")){
                    /**
                     * 订单状态更新
                     *    参数: 订单编号  支付宝支付流水  订单金额
                     *   订单更新思路
                     *     I.参数校验
                     *       1.订单记录查询
                     *       2.记录存在校验
                     *       3.订单支付状态校验(未支付)
                     *       4.订单金额校验
                     *     II.订单状态更新
                     */
                    Order order = orderService.selectOrderByOrderSn(outTradeNo);
                    if(null == order){
                        return BaseResult.error("订单记录不存在!");
                    }

                    if(order.getPayStatus().equals(PayStatus.has_payed.getStatus())){
                        return BaseResult.success();
                    }

                    if(order.getTotalAmount().compareTo(totalAmount) !=0){
                        return BaseResult.error("订单金额异常!");
                    }

                    // 设置订单支付状态为已支付
                    order.setPayStatus(PayStatus.has_payed.getStatus());
                    order.setShippingStatus(ShipStatus.has_send.getStatus());
                    order.setPayCode(tradeNo);
                    order.setPayName("支付宝支付");
                    //order.setPayTime(new Date());
                    if(orderMapper.updateByPrimaryKeySelective(order) !=1){
                        return  BaseResult.error("订单支付异常，请联系客服!");
                    }
                    return BaseResult.success();
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return BaseResult.error();
    }
}
